<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

/**
 * @package		Joomla
 * @subpackage	JobBoard
 */
defined('_JEXEC') or die('Restricted access'); 
error_reporting(E_ALL ^ E_NOTICE);


	// Execute query string
	function fcnQuerySQL($sql){
		$db =& JFactory::getDBO();
		$db->setQuery($sql);
		return $db->loadAssocList();
	}
	
	// Generate XML file from FeedID
	function fcnGenerateXMLFile($feedID) {
		
		$db =& JFactory::getDBO();	
		
		if (!is_numeric($feedID)) return;
	
		$sql = "SELECT * from #__ja_xml_feeds WHERE FeedID='".fcnGetStandardSQL($feedID)."' ";
		$db->setQuery($sql);
		$result = fcnQuerySQL($sql);
		
		$feedRow = $result[0];
		
		$feedRow['MetaData'] = unserialize($feedRow['MetaData']);
		
		// Build search condition.
		$where_sql = "";
		
		$strLocation="";
		if($feedRow['search_location'] != ""){
			$arrLocation = explode(",", $feedRow['search_location']);		
			foreach ($arrLocation as $k=>$v){
				$strLocation .= " id = '".$v."' OR ";
			}
			$strLocation .= "1 > 1";
		}
		if($strLocation != "1 > 1" && $strLocation != "")
			$strLocation = " AND (a.location_id IN (SELECT id FROM #__ja_location WHERE $strLocation ))";
		
		$strCategory="";
		if($feedRow['search_category'] != ""){
			$arrCategory = explode(",", $feedRow['search_category']);		
			foreach ($arrCategory as $k=>$v){
				$strCategory .= " id = '".$v."' OR ";
			}
			$strCategory .= "1 > 1";
		}
		if($strCategory != "1 > 1"  && $strCategory != "")
			$strCategory = " AND (a.cat_id IN (SELECT id FROM #__ja_categories WHERE $strCategory ))";
		
		$strType = "";
		if($feedRow['search_type'] != ""){
			$arrType = explode(",", $feedRow['search_type']);		
			foreach ($arrType as $k=>$v){
				$strType .= " a.job_type like '%".$v."%' OR ";
			}
			$strType .= "1 > 1";
		}
		if($strType != "1 > 1" && $strType != "")
			$strType = " AND ( $strType )";
		
		$strTitle = "";
		if($feedRow['search_title'] != ""){
			$arrTitle = explode(",", $feedRow['search_title']);		
			foreach ($arrTitle as $k=>$v){
				$strTitle .= " a.title like '%".$v."%' OR ";
			}
			$strTitle .= "1 > 1";
		}
		if($strTitle != "1 > 1"  && $strTitle != "")
			$strTitle = " AND ( $strTitle )";
		
		$strDes = "";
		if($feedRow['search_description'] != ""){
			$arrDes = explode(",", $feedRow['search_description']);		
			foreach ($arrDes as $k=>$v){
				$strDes .= " a.job_detail '%".$v."%' OR ";
			}
			$strDes .= "1 > 1";
		}
		if($strDes != "1 > 1"  && $strDes != "")
			$strDes = " AND ( $strDes )";
		
		$limit = "";
		if ($feedRow['TotalRecords'] > 0) {
			$limit = "LIMIT ".addslashes($feedRow['TotalRecords']);
		}
		
		// Gzip compress the output, if supported by PHP & the browser
		if (function_exists('ob_gzhandler')) {
			ob_start("ob_gzhandler");
		} else {
			ob_start();
		}
		header('Content-type: application/xml; charset=UTF-8');
		if (JRequest::getVar('download') != '') {
			header('Content-Disposition: attachment; filename="'.$feedID.'.xml"');
		}
		
		$sql = "SELECT a.*, b.*, a.id as jobid from #__ja_jobs a LEFT JOIN #__users b ON a.user_id = b.id  WHERE 1=1 $strCategory $strDes $strLocation $strTitle $strType 
				ORDER BY a.id DESC $limit ";
		
		$db =& JFactory::getDBO();
		$db->setQuery($sql);
		$records = $db->query();
		
		// Create xml_exportxml_export directory in: site/components/com_jajobboard/uploads/
		jimport('joomla.filesystem.folder');
		jimport('joomla.filesystem.file');
		
		global $jbconfig;
		
		$dir = JPATH_SITE.$jbconfig['general']->get('upload_folder',DS.'images'.DS.'stories'.DS.'jbuploads');
		
		if(!JFolder::exists($dir)){
			JFolder::create($dir);
		}
		
		$filename = $dir.DS.str_replace(" ", "", $feedRow['FeedID'].$feedRow['FeedName']).".xml";
		
		// Generate the XML feed & cache the result.
		echo '<?xml version="1.0" encoding="UTF-8" ?>';
		
		fcnGenerateXMLData($feedRow, '0', $records, $data);
		$output = ob_get_contents();
		JFile::write($filename, $output);
		ob_end_flush();
	}
	

	// Generate XML structure and data
	function fcnGenerateXMLData(&$feedRow, $elementID, &$records, &$data, $searchPivot=false) {
		// Declare variable
		static $xmlDepth=0;
		static $isHaveRecords = false;
		static $implodeState = false;
		static $stackData = array();
		static $implodeElementID;
		$isEnd = false;
		
		if ($xmlDepth > 100) return;
	
		$sql = "select * from #__ja_xml_schemas_details WHERE `ParentID`='".fcnGetStandardSQL($elementID)."' AND `SchemaID`='".fcnGetStandardSQL($feedRow['SchemaID'])."' ORDER BY IsPivot DESC "; // order by IsPivot to ensure that this row is last.
			
		$db =& JFactory::getDBO();
		$db->setQuery($sql);
		$result = $db->query();
		
		if (mysql_num_rows($result) > 0) {		
			$isEnd = true; 
		}
		
		$isNewLine = false;
			
		while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {	
			// Searching for pivot record
			while ( ($searchPivot==true) && ($row['IsPivot']!='Y') ) {
				$row = mysql_fetch_array($result, MYSQL_ASSOC);
			}
			
			if (isset($feedRow['MetaData']['StaticData_'.$row['ElementID']])) {
				$row['StaticData'] = $feedRow['MetaData']['StaticData_'.$row['ElementID']];
			}
			$element = $row['ElementName'];
			if ($row['FieldAttributes']!='') {
				$row['FieldAttributes'] = " ".$row['FieldAttributes'];
			}
			
			if ($row['IsPivot']=='Y') {
				$pivotParentID = $row['ParentID'];			
				if ($data = mysql_fetch_array($records, MYSQL_ASSOC)) {
					$sql = "SELECT * FROM #__users WHERE id = '".fcnGetStandardSQL($data['user_id'])."' LIMIT 1";
					$ac_result = fcnQuerySQL($sql);
					$ac_row = $ac_result[0];
					
					foreach ($ac_row as $key => $value) {
						$data['Employer_'.$key] = $value; 
						unset($ac_row[$key]);
					}
				} else {
					$isHaveRecords = true; 
					return;
				}
			}
	
			if (!fcnIsEmptyField($feedRow, $row, $data)){
				if (!$isNewLine) {
					if (!$implodeState) echo "\n";
					$isNewLine = true;
				}	
				if (!$implodeState) fcnPrintSpaceRepeat($xmlDepth);
				if (!$implodeState) {
					echo "<$element".($row['FieldAttributes']).">";
				}
				if (isset($feedRow['MetaData']['implode_'.$row['ElementID']])) {
					if($feedRow['MetaData']['implode_'.$row['ElementID']] == "Y"){
						$implodeState = true; 
						$implodeElementID=$row['ElementID'];
					}
				}
				$xmlDepth+=1;			
				$ending = fcnGenerateXMLData($feedRow, $row['ElementID'], $records, $data);			
				$value = '';			
				if ($ending) {
					
				} else { 
	
					$value = '';
					if (($row['StaticData']=='') || ($row['StaticMod']!='F')) {
						$value = fcnGetData($row, $feedRow, $data);
						if ($row['NumField']>1) { # extra
							$comma='';
							for ($i=1; $i < 5; $i++) {
								$extra_field_id = ''; 
								$extra_field_id = $feedRow['MetaData']['mf_'.$i.'_extra_'.$row['ElementID']];
								if ($extra_field_id!='') {
									$value = $value.', '.fcnGetData($row, $feedRow, $data, $extra_field_id);
								}
							}
						}
					}
					
					if ($row['StaticData']!='') {
						$s_val = '';
						$s_val = fcnGetStaticData($row['FormID'], $data, $row['StaticData'], $feedRow);
						if ($row['StaticMod']=='P') {
							$value = $s_val.$value;
						} elseif ($row['StaticMod']=='A') { 
							$value = $value.$s_val;
						} else {
							$value = $s_val; 
						}
					}
					if ($row['IsCDATA']=='Y') {
						$value = str_replace(']]>', ']]]]><![CDATA[>', $value); 
						$value = '<![CDATA['.utf8_encode($value).']]>';					
					} else {
						$value =  fcnXMLEntities($value);
					}
					if (($implodeState) && ($value)) {
						$stackData[] = $value;
					} else {
						echo trim($value);			
					}
				}
					if ($implodeState && ($implodeElementID==$row['ElementID'])) {
						$implodeState=false;
						$str = implode (',',$stackData);
						$stackData = array();
						echo $str;
					}
					if (!$implodeState) {
						echo "</$element>";
						echo "\n";
					}
			}
			if ($row['IsPivot']=='Y'){
				if ($isHaveRecords==false) {
					fcnGenerateXMLData($feedRow, $pivotParentID, $records, $data, true);
				}
				if ($searchPivot) { 
					break;
				}			
			}
		}
		$xmlDepth-=1;
		return $isEnd;
	}

	// Check emtyp field
	function fcnIsEmptyField(&$feedRow, &$row, &$data) {	
		return false;		
		if ($row['IsParent']=='Y') {
			return false;
		}
		if (($row['StaticData']!='') && ($row['StaticMod']=='F')) {
			return false;
		}
		$fieldID = $feedRow['MetaData'][$row['ElementID']];
		if (($data[$fieldID]=='') && ($fieldID!='')) {
			return true;
		}
		return false;
	}
	
	// Get field name from ID
	function returnFieldNameFromID($id){		
		require_once(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_jajobboard'.DS.'asset'.DS.'rendfield.php');
		$editList = getEditFieldList("ja_jobs", " AND f.id = ".$id);
		if(count($editList) > 0){
			return $editList[0]->field_name;
		}				
		$data = array(
			"9991" => "name",
			"9992" => "email",
			"9993" => "company",
			"9994" => "address",
			"9995" => "website",
			"9996" => "tel"
			);
		if(isset($data[$id]))
			return $data[$id];
		else return "";
	}
	
	// Truncate HMTL string	
	function fcnTruncateHTML ($s, $MAX_LENGTH, &$strLength) {
		$strLength=0;
		if (func_num_args()>3)
			$add_ellipsis = func_get_arg(3);
		else
			$add_ellipsis = true;
	
		if (func_num_args()>4) 
			$with_tags = func_get_arg(4);
		else
			$with_tags = false;
			
		$tag_expr = "";
		if ($with_tags)
			$tag_expr = "|<[^>]+>";
	
		$offset = 0; $CharCount=0;
		$str = "";
		while ((preg_match ('/(&#?[0-9A-z]+;'.$tag_expr.'|.|\n)/', $s, $maches, PREG_OFFSET_CAPTURE, $offset) && ($CharCount < $MAX_LENGTH))) {
			$offset += strlen($maches[0][0]);
			$CharCount++;
			$str .= $maches[0][0];	
		}
		
		if (($CharCount == $MAX_LENGTH)&&($add_ellipsis))
			$str = $str."...";
		
		$strLength = $CharCount;
		return $str; 
	}

	// Get data from MySQL
	function fcnGetData(&$elementRow, &$feedRow, &$data, $fieldID='') {
		if ($fieldID=='' && isset($feedRow['MetaData'][$elementRow['ElementID']])) {
			$fieldID = $feedRow['MetaData'][$elementRow['ElementID']];
		}else 
			$fieldID = 1;
		
		if(returnFieldNameFromID($fieldID) != ""){
			if(isset($data[returnFieldNameFromID($fieldID)]))
				$value = trim($data[returnFieldNameFromID($fieldID)]);
			else{
				return "";
			}
		}else 
			return "";
	
		if ($fieldID=='summary') {
			global $arrTagToField;
			$description =  trim($data[$arrTagToField['DESCRIPTION']['field_id']]);
			$value  = str_replace ('&nbsp;', ' ', fcnTruncateHTML (strip_tags($description),  JB_POSTS_DESCRIPTION_CHARS, $strLength));
			return $value;
		}
		
		if(isset($feedRow['MetaData']['ft_'.$elementRow['ElementID']]))
			$fieldType = $feedRow['MetaData']['ft_'.$elementRow['ElementID']];
		else 
			$fieldType = "TEXT";
		
		if ($elementRow['IsStripTag']=='Y') {
			$value = (strip_tags($value));
			$fromHTML = array("&nbsp;", "  ", "\n\n", "\r\n\r\n");
			$to_text = array(" ", " ", "\n", "\n");
			$value = str_replace($fromHTML, $to_text, $value);
		} 
	
		if ($elementRow['NumTruncate']>0) {
			$value = fcnTruncateHTML ($value,  $elementRow['NumTruncate'], $strLength, false);
		}
		
		switch ($fieldType) {
			case 'MSELECT':
			case 'CHECK':
				if ($elementRow['CodeProType']=='Y') {
					$values = explode (",", $value);
					$comma = ''; $str;
					if (sizeof($values)>0) {
						foreach ($values as $v) {
							$str .= $comma.JB_getCodeDescription ($fieldID, $v);
							$comma = ", ";
						}
					}
					$value = $str;
				}
				break;
			case 'SELECT':
			case 'RADIO':
				if ($elementRow['CodeProType']=='Y') {
					$value = JB_getCodeDescription ($fieldID, $value);
				}
				break;
			case 'CATEGORY':
				if ($elementRow['CatProType']=='Y' || $elementRow['CodeProType']=='Y') {
					$arrID = explode(",", $value);
					$value = array();
					foreach($arrID as $val){
						$value[] = fcnGetCategoryName($fieldID, trim($val));
					}
					$value = implode(", ",$value);
				}
				break;
		}
	
		if ($elementRow['IsBoolean']=='Y') {
			$match = $feedRow['MetaData']['boolean_p_'.$elementRow['ElementID']];
			if (($fieldType=='MSELECT') || ($fieldType=='RADIO')) {
				if (strpos(strtolower($value), strtolower($match))!==false)
					$value = 'true';
				else
					$value = 'false';
			} else {
				if (strtolower($value) == strtolower($match))
					$value = 'true';
				else
					$value = 'false';
			}
		}
		return $value;
	}
	
	// Get category name from ID
	function fcnGetCategoryName($fieldID, $fieldValue){
		$db =& JFactory::getDBO();
		
		require_once(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_jajobboard'.DS.'asset'.DS.'rendfield.php');
		$editList = getEditFieldList("ja_jobs", " AND f.id = ".$fieldID);
		if(count($editList) > 0){
			if($editList[0]->is_referred){
				$sql = "SELECT ".$editList[0]->referred_value." FROM #__".$editList[0]->referred_table." WHERE ".$editList[0]->referred_key." = '".$fieldValue."' ";
			}else{
				$sql = "SELECT text FROM #__ja_codes WHERE value = '".$fieldValue."' AND field_id = 'ja_jobs_".$editList[0]->field_name."' ";
			}
			$db->setQuery($sql);
			return $db->loadResult();
		}
		return "";
	}
	
	// Get static data value
	function fcnGetStaticData($formID, &$data, $value, &$feedRow) {
		global $prams, $mainframe;
		$prams = $data; 
		if (!preg_match('/%[a-z_]+%/i', $value)) {
			return $value; 
		}
		
		$value = str_replace('%SITE_NAME%', $mainframe->getCfg('sitename') , $value);
		$value = str_replace('%SITE_DESCRIPTION%',  $mainframe->getCfg('MetaDesc'), $value);
		$value = str_replace('%SITE_CONTACT_EMAIL%', $mainframe->getCfg('mailfrom'), $value);
		$value = str_replace('%BASE_HTTP_PATH%', JURI::root(), $value);
		$value = str_replace('%DEFAULT_LANG%', $mainframe->getCfg('language'), $value);	
		$value = str_replace('%FEED_DATE%', date('r'), $value);		
		$value = str_replace('%RSS_FEED_LOGO%', "", $value);
		$value = str_replace('%RSS_LOGO_HEIGHT%', "", $value);
		$value = str_replace('%RSS_LOGO_WIDTH%', "", $value);	
		
		switch ($formID) {
			case '1':
				$post_time = strtotime($data['created_date']." GMT ");
				$link = JURI::root().'index.php?option=com_jajobboard&view=jajobs&layout=jaview&cid[0]='.$data['jobid'];			
				$value = str_replace('%LINK%', $link, $value);
				$value = str_replace('%DATE%', date('Y-m-d', $post_time), $value);
				$value = str_replace('%DATE_RFC%', date('r', $post_time), $value);
				$value = str_replace('%EXPIRE_DATE%', date('Y-m-d'), $value);
				break; 
			case '2':
				break;
		}
		return $value;
	}
	
	// Replace entities
	function fcnXMLEntities($str, $quote_style=ENT_COMPAT){
		$str = fcnHTMLEntityDecode($str);
		$trans = array(
			"<" => '&lt;', 
			"&" => '&amp;', 
			">" => '&gt;', 
			'"' => '&quot;',  
			'\'' => '&apos;');
		$str = strtr($str, $trans);
		return $str;  
	} 
	
	// Convert code to UTF-8 string
	function fcnCodeToUTF8($strNumber){
		if ($strNumber < 128) return chr($strNumber);
		if ($strNumber < 2048) return chr(($strNumber >> 6) + 192) . chr(($strNumber & 63) + 128);
		if ($strNumber < 65536) return chr(($strNumber >> 12) + 224) . chr((($strNumber >> 6) & 63) + 128) . chr(($strNumber & 63) + 128);
		if ($strNumber < 2097152) return chr(($strNumber >> 18) + 240) . chr((($strNumber >> 12) & 63) + 128) . chr((($strNumber >> 6) & 63) + 128) . chr(($strNumber & 63) + 128);
		return '';
	}
	
	// Decode HMTL string
	function fcnHTMLEntityDecode($str) {
		return preg_replace('/&#(\\d+);/e', 'fcnCodeToUTF8($1)', utf8_encode($str));
		static $trans_tbl;
		$str = preg_replace('~&#x([0-9a-f]+);~ei', 'fcnCodeToUTF8(hexdec("\\1"))', $str);
		$str = preg_replace('~&#([0-9]+);~e', 'fcnCodeToUTF8(\\1)', $str);
		if (!isset($trans_tbl)){
			$trans_tbl = array();
			foreach (get_html_translation_table(HTML_ENTITIES) as $value=>$key)
				$trans_tbl[$key] = utf8_encode($value);
		}
		return strtr($str, $trans_tbl);
	}
	
	// Print space characters
	function fcnPrintSpaceRepeat ($i) {
		for ($x=0; $x < $i; $x++) {
			echo "  ";
		}
	}
	
	// Print space characters
	function fcnPrintSpace ($i) {
		for ($x=0; $x < $i; $x++) {
			echo "&nbsp;&nbsp;";
		}
	}
	
	// To standard SQL string
	function fcnGetStandardSQL($str){
		return mysql_real_escape_string($str);
	}

	// To standard HTML string
	function fcnEscapeHTML ($str, $amp=false) {
		$str = (string) $str;
		$trans = array(
			"<" => '&lt;', 
			">" => '&gt;', 
			'"' => '&quot;',
			'(' => '&#40;',
			')' => '&#41;',
			'& ' => '&amp; ',		
			);
		if ($amp) $trans['&']= '&amp;';
		return strtr($str, $trans);
	}
	
	// Show select job field
	function fcnShowSelectField($formID, $seleted="", $prefix=""){
		// Job information options
		require_once(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_jajobboard'.DS.'asset'.DS.'rendfield.php');
		$editList = getEditFieldList("ja_jobs");
		$str = '<optgroup label="Job Information">';
		foreach ($editList as $row){
			$se = ($seleted == $row->id)?'selected="selected"':"";
			$str .= '<option '.$se.' value="'.$row->id.'">'.$row->label.'</option>';
		}
		
		// Employee information option
		$str .= '</optgroup><optgroup label="User Information">';
		
		$se = ($seleted == "9991")?'selected="selected"':"";
		$str .= '<option '.$se.' value="9991">Full Name</option>';
		
		$se = ($seleted == "9992")?'selected="selected"':"";
		$str .= '<option '.$se.' value="9992"">E-mail</option></optgroup>';
		
		$se = ($seleted == "9993")?'selected="selected"':"";
		$str .= '<optgroup label="Company Information"><option '.$se.' value="9993">Company name</option>';
		
		$se = ($seleted == "9994")?'selected="selected"':"";
		$str .= '<option '.$se.' value="9994">Company address</option>';
		
		$se = ($seleted == "9995")?'selected="selected"':"";
		$str .= '<option '.$se.' value="9995">Company website</option>';
		
		$se = ($seleted == "9996")?'selected="selected"':"";
		$str .= '<option '.$se.' value="9996">Company phone</option></optgroup>';
		// Print string
		echo $str;
	}

	function fcnGetSelectField(&$row, &$feedRow) {
		if ($row['StaticMod']=='P') {
			echo "<font color='maroon'><b>".$row['StaticData']."</b></font>";
		}
	
		?>
		<select name="field_id_<?php echo $row['ElementID'];?>" id="field_id_<?php echo $row['ElementID'];?>" >
			<option value='0'>[None]</option>
			<?php
			fcnShowSelectField ($row['FormID'], JRequest::getVar('field_id_'.$row['ElementID'],""));
			if(isset($feedRow['include_emp_accounts'])){
				if (($feedRow['include_emp_accounts'] == 'Y') && ($feedRow['publish_mode'] != 'PUB')) {
					?>
					<option value='0' style="color: gray;">Employer's Accounts:</option>
					<?php
					fcnShowSelectField (4, JRequest::getVar('field_id_'.$row['ElementID'],""), $prefix='Employer_');
				}
			}
		?>
		</select>
		<?php
		if ($row['NumField']>1) {
			for ($i=1; $i < $row['NumField']; $i++) {
				?>
				<select name="mf_<?php echo $i;?>_extra_<?php echo $row['ElementID'];?>" >
					<option value=''>[None]</option>
					<?php
					fcnShowSelectField($row['FormID'], $_REQUEST['mf_'.$i.'_extra_'.$row['ElementID']]);
				?>
				</select>
			<?php
			}
		}
	}
?>